<template>
  <section>
    <!--工具条：关键字查询 + 新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">关键字查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success"  @click="handleAdd">新增</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="menus" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60" label="序号" >

      </el-table-column>
      <el-table-column prop="name" label="菜单名称" width="130" sortable>
      </el-table-column>
      <el-table-column prop="component" label="菜单路径" width="260" sortable>
      </el-table-column>
      <el-table-column prop="url" label="访问URL" width="260" sortable>
      </el-table-column>
      <el-table-column prop="icon" label="图标" width="120" sortable>
      </el-table-column>
      <el-table-column prop="index" label="排序索引" width="120" sortable>
      </el-table-column>
      <el-table-column  label="上级菜单" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.parent" style="color: green">{{scope.row.parent.name}}</span>
          <span v-else style="color: red">无上级菜单</span>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="简介" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: hotpink">正常</span>
          <span v-else style="color: blue">禁用</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button size="small" type="warning"  @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="small" type="danger"  @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增/修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" prop="component">
          <el-input v-model="saveForm.component" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="访问URL" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="saveForm.icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item  label="排序"prop="index">
            <el-input-number v-model="saveForm.index"  :min="1" :max="10" ></el-input-number>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="true" aria-checked="true">正常</el-radio>
            <el-radio class="radio" :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上级部门">
          <!--
            el-cascader - 级联框
            v-model="saveForm.parent_id" - 双向绑定

              label: 'name', - 回显哪一个属性值
                value: 'id' - 传值哪一个属性值
            回显机制【修改】：
              1.定位：v-model="saveForm.parent_id" 与 deptTree中的每一个对象的id 定位
              2.显示哪一个属性值：label: 'name',  回显对象的name属性值
            传值机制：
              ？？
          -->
          <el-cascader v-model="saveForm.parentId"
                       :options="menuTree"
                       :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id'
              }"
                       clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {

      //1..分页显示所属数据
      menus: [],          //列表数据
      listLoading: false, //加载框
      currentPage: 1,     //当前页
      pageSize: 5,        //每页显示的条数
      totals: 0,          //总数量

      //2.高级查询所需数据
      keyword: null,

      //3.批量删除的相关数据
      sels: [],//列表选中列

      //4.添加或修改的相关数据
      title: null,
      saveFormVisible: false,//控制对话框是否显示 - 默认不显示
      saveLoading: false,     //保存的加载框 - 默认不显示
      saveFormRules: {         //表单项验证
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        component: [
          { required: true, message: '请输入菜单组件路径：例如/org/Department', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入路径：路由中当前组件的path路径', trigger: 'blur' }
        ],

      },
      //5.添加和修改中对话框的数据
      saveForm: {
        id:null,
        name:'',
        component:'',
        url:'',
        icon:'',
        index:null,
        parentId:null,
        intro:'',
        state:true
      },
      //6.显示部门树
      menuTree: []


    }
  },
  methods: {
    //1.获取列表
    getMenus(){
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;//显示加载框
      this.$http.post("/menu",para).then(res=>{
        this.menus = res.data.data;//给数组赋值 - 显示列表数据
        this.totals = res.data.totals;//给总数量赋值 - 计算分页栏
        this.listLoading = false;//关闭加载框
      }).catch(res => {
        this.$message.error("获取分页数据失败!!!");
      })
    },

    //2..分页查询 - 点击某一页查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getMenus();//列表
    },

    //3.高级查询 = 关键字查询
    keywordQuery(){
      //防止当前页不在第一页的时候 通过关键字查询出现 当前页没有数据的情况
      this.currentPage = 1;
      this.getMenus();
    },


    //4..删除功能逻辑
    handleDel: function (index, row) {
      //elementUi提供确认框 - 点确定之后执行then里面的代码，点击取消执行catch中的逻辑
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//显示加载框
        this.$http.delete("/menu/" + row.id).then(res => {
          this.listLoading = false;//关闭加载框
          if(res.data.success){
            this.$message.success("删除成功"); //提示成功消息
            //计算总页数
            //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
            var totalPage = Math.ceil(this.totals/this.pageSize); //总页数 = 最后一页
            //如果当前页是最后一页                  并且是最后一条数据                  并且不是第一页
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getMenus();
          }else{
            this.$message.error("删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
        //确认框点击取消之后走这里
      });
    },

    //5.批量操作获取选中的数据
    selsChange: function (sels) {
      this.sels = sels;
    },


    //6.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/menu",ids).then(res => {
          this.listLoading = false;
          if(res.data.success){
            this.currentPage = 1;
            this.getMenus();
          }else{
            this.$message.error("批量删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
      });
    },

    //7.点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "编辑";
      this.saveForm = Object.assign({}, row); //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝一份给{}
      this.saveFormVisible = true; //弹出对话框
      //获取部门树
      this.getDeptTree();

    },

    //8.点击添加按钮弹出模态框
    handleAdd: function () {
      this.title = "添加";
      this.saveForm = {
        id:null,
        name:'',
        component:'',
        url:'',
        icon:'',
        index:null,
        parentId:null,
        intro:'',
        state:true
      };
      this.saveFormVisible = true;
      //获取部门树
      this.getDeptTree();
    },

    //9..点击模态框提交数据
    saveSubmit: function () {
      //表单验证：只要表单项中任何一个验证不通过，都不能点击提交
      //所有的ref中名称为saveForm的表单
      this.$refs.saveForm.validate((valid) => {
        if (valid) {//表单验证通过 => 每一个表单项都通过了
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            //对无限级树 上级部门 的处理 - 没有无限级树不需要处理
            //1.不修改上级部门，没有点级联框：2
            //2.不修改上级部门，点了级联框选择过其他部门：[ 2 ]
            //3.去掉上级部门：[]
            //4. [ 3, 9, 12 ]
            //5. null
            //处理宠物类型id
            let arr = para.parentId;
            if(arr && arr.length==0){
              para.parentId = null;
            }
            if(arr && arr.length>0){ //[1,13]
              para.parentId = arr[arr.length-1];
            }

            this.$http.put("/menu",para).then(res => {

              this.saveFormVisible = false;//关闭对话框
              this.saveLoading = false; //关闭加载框
              if(res.data.success){
                this.getMenus();    //重新加载新的数据
              }else{
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.saveLoading = false;  //关闭加载框
              this.saveFormVisible = false; //关闭对话框
              this.$message.error("系统繁忙，请稍后重试!!![400,404]");
            })
          });
        }
      });
    },

    //10.获取部门树
    getDeptTree(){
      this.$http.get("/menu/menuTree").then(res=>{
        this.menuTree = res.data;
      })
    }

  },
  mounted() {
    this.getMenus();
  }
}

</script>

<style scoped>

</style>